<template>
  <view class="container">
    <view class="toolbar">
      <view class="tool-group">
        <button 
          :class="{ active: currentTool === 'pen' }" 
          @tap="setTool('pen')"
        >画笔</button>
        <button 
          :class="{ active: currentTool === 'arrow' }" 
          @tap="setTool('arrow')"
        >箭头</button>
      </view>
      <view class="tool-group">
        <button @tap="clearCanvas">清除</button>
      </view>
    </view>
    
    <canvas 
      type="2d"
      id="drawingCanvas"
      class="canvas"
      :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }"
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
    ></canvas>
  </view>
</template>

<script>
export default {
  data() {
    return {
      canvasWidth: 300,
      canvasHeight: 400,
      ctx: null,
      currentTool: 'pen',
      shapes: [],
      currentShape: null,
      startPoint: null,
      isDrawing: false,
      minDragDistance: 5
    }
  },
  
  onReady() {
    this.initCanvas()
  },
  
  methods: {
    async initCanvas() {
      const query = uni.createSelectorQuery()
      query.select('#drawingCanvas')
        .fields({ node: true, size: true })
        .exec((res) => {
          const canvas = res[0].node
          const ctx = canvas.getContext('2d')
          
          // 设置 canvas 大小
          const dpr = uni.getSystemInfoSync().pixelRatio
          canvas.width = this.canvasWidth * dpr
          canvas.height = this.canvasHeight * dpr
          ctx.scale(dpr, dpr)
          
          this.ctx = ctx
          this.canvas = canvas
        })
    },
    
    setTool(tool) {
      this.currentTool = tool
    },
    
    handleTouchStart(e) {
      const touch = e.touches[0]
      const x = touch.x
      const y = touch.y
      
      this.startPoint = { x, y }
      this.isDrawing = true
      this.currentShape = null
    },
    
    handleTouchMove(e) {
      if (!this.isDrawing || !this.startPoint) return
      
      const touch = e.touches[0]
      const x = touch.x
      const y = touch.y
      
      // 计算移动距离
      const dx = x - this.startPoint.x
      const dy = y - this.startPoint.y
      const distance = Math.sqrt(dx * dx + dy * dy)
      
      // 如果移动距离小于最小距离，不进行绘制
      if (distance < this.minDragDistance) return
      
      // 开始绘制新图形
      if (!this.currentShape) {
        if (this.currentTool === 'pen') {
          this.currentShape = {
            type: 'pen',
            points: [[this.startPoint.x, this.startPoint.y], [x, y]],
            stroke: '#000000',
            lineWidth: 2
          }
          this.shapes.push(this.currentShape)
        } else if (this.currentTool === 'arrow') {
          this.currentShape = {
            type: 'arrow',
            start: { x: this.startPoint.x, y: this.startPoint.y },
            end: { x, y },
            stroke: '#000000',
            lineWidth: 2
          }
          this.shapes.push(this.currentShape)
        }
      } else {
        // 更新现有图形
        if (this.currentTool === 'pen') {
          this.currentShape.points.push([x, y])
        } else if (this.currentTool === 'arrow') {
          this.currentShape.end = { x, y }
        }
      }
      
      this.redraw()
    },
    
    handleTouchEnd() {
      this.isDrawing = false
      this.startPoint = null
      this.currentShape = null
    },
    
    redraw() {
      if (!this.ctx) return
      
      // 清除画布
      this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight)
      
      // 绘制所有图形
      this.shapes.forEach(shape => {
        this.ctx.strokeStyle = shape.stroke
        this.ctx.fillStyle = shape.stroke
        this.ctx.lineWidth = shape.lineWidth
        this.ctx.lineCap = 'round'
        this.ctx.lineJoin = 'round'
        
        if (shape.type === 'pen') {
          this.ctx.beginPath()
          this.ctx.moveTo(shape.points[0][0], shape.points[0][1])
          for (let i = 1; i < shape.points.length; i++) {
            this.ctx.lineTo(shape.points[i][0], shape.points[i][1])
          }
          this.ctx.stroke()
        } else if (shape.type === 'arrow') {
          this.drawArrow(shape.start, shape.end, shape.lineWidth)
        }
      })
    },
    
    drawArrow(start, end, lineWidth) {
      const headLength = 10
      const angle = Math.atan2(end.y - start.y, end.x - start.x)
      
      // 绘制箭头主体
      this.ctx.beginPath()
      this.ctx.moveTo(start.x, start.y)
      this.ctx.lineTo(end.x, end.y)
      this.ctx.stroke()
      
      // 绘制箭头头部
      this.ctx.beginPath()
      this.ctx.moveTo(end.x, end.y)
      this.ctx.lineTo(
        end.x - headLength * Math.cos(angle - Math.PI / 6),
        end.y - headLength * Math.sin(angle - Math.PI / 6)
      )
      this.ctx.lineTo(
        end.x - headLength * Math.cos(angle + Math.PI / 6),
        end.y - headLength * Math.sin(angle + Math.PI / 6)
      )
      this.ctx.closePath()
      this.ctx.fill()
    },
    
    clearCanvas() {
      this.shapes = []
      this.redraw()
    }
  }
}
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx;
}

.toolbar {
  display: flex;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.tool-group {
  display: flex;
  gap: 10rpx;
}

button {
  padding: 10rpx 20rpx;
  font-size: 28rpx;
  background-color: #ffffff;
  border: 1px solid #dddddd;
  border-radius: 8rpx;
}

button.active {
  background-color: #007AFF;
  color: #ffffff;
  border-color: #007AFF;
}

.canvas {
  background-color: #ffffff;
  border: 1px solid #dddddd;
  border-radius: 8rpx;
}
</style> 